package com.yupi.yupicturebackend.manager;


import cn.hutool.core.date.DateUtil;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.RandomUtil;
import cn.hutool.http.HttpResponse;
import cn.hutool.http.HttpUtil;
import cn.hutool.http.Method;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.qcloud.cos.model.PutObjectResult;
import com.qcloud.cos.model.ciModel.persistence.ImageInfo;
import com.yupi.yupicturebackend.config.CosClientConfig;
import com.yupi.yupicturebackend.exception.BusinessException;
import com.yupi.yupicturebackend.exception.ErrorCode;
import com.yupi.yupicturebackend.exception.ThrowUtils;
import com.yupi.yupicturebackend.model.dto.file.UploadPictureResult;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpStatus;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import javax.annotation.Resource;
import java.io.File;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Arrays;
import java.util.Date;
import java.util.List;


/**
 * 文件管理器
 * @deprecated  废弃,改为使用upload的模板方法
 */
@Slf4j
@Service
@Deprecated
public class FileManager {

    @Resource
    private CosClientConfig cosClientConfig;

    @Resource
    private CosManager cosManager;

    /**
     * 上传图片
     * @param multipartFile
     * @param uploadPathPrefix
     * @return
     */
    public UploadPictureResult uploadPicture(MultipartFile multipartFile, String uploadPathPrefix) {
        // 校验图片
        validPicture(multipartFile);
        // 图片上传地址
        String uuid = RandomUtil.randomString(8);
        // 文件名
        String fileName = String.format("%s_%s.%s", DateUtil.formatDate(new Date()), uuid, multipartFile.getOriginalFilename());
        String filepath = String.format("/%s/%s", uploadPathPrefix, fileName);
        File file = null;
        try {
            // 创建临时文件
            file  = File.createTempFile(filepath, null);
            multipartFile.transferTo(file);
            // 上传文件
            PutObjectResult putObjectResult = cosManager.putPictureObject(filepath, file);
            // 解析结果
            ImageInfo imageInfo = putObjectResult.getCiUploadResult().getOriginalInfo().getImageInfo();
            // 返回结果
            UploadPictureResult uploadPictureResult = new UploadPictureResult();
            uploadPictureResult.setUrl(cosClientConfig.getHost() +"/"+ filepath);
            uploadPictureResult.setPicName(fileName);
            uploadPictureResult.setPicSize(multipartFile.getSize());
            uploadPictureResult.setPicWidth(imageInfo.getWidth());
            uploadPictureResult.setPicHeight(imageInfo.getHeight());
            double scale = (double) imageInfo.getWidth() / (double) imageInfo.getHeight();
            uploadPictureResult.setPicScale(scale);
            uploadPictureResult.setPicFormat(imageInfo.getFormat());
            return uploadPictureResult;
        } catch (Exception e) {
            log.info("图片上传失败" ,e);
            throw new BusinessException(ErrorCode.SYSTEM_ERROR, "上传失败");
        }finally {
            deleteTempFile(file);
            }
        }


    /**
     * 校验图片
     * @param multipartFile
     */
    private void validPicture(MultipartFile multipartFile) {
        ThrowUtils.throwIf( multipartFile==null, ErrorCode.PARAMS_ERROR,"上传图片不能为空");
        // 校验文件大小
        ThrowUtils.throwIf( multipartFile.getSize() > 1024 * 1024 * 2, ErrorCode.PARAMS_ERROR,"上传图片不能大于2M");
        // 校验文件后缀
        String suffix = FileUtil.getSuffix(multipartFile.getOriginalFilename());
        final List<String> fileSuffixList = Arrays.asList("jpg", "jpeg", "png", "wpeg");
        ThrowUtils.throwIf(!fileSuffixList.contains(suffix), ErrorCode.PARAMS_ERROR,"上传图片格式不正确");
    }

    /**
     * 删除临时文件
     */
    private void deleteTempFile(File file) {
        if (file != null) {
            // 删除临时文件
            boolean delete = file.delete();
            if (!delete) {
                log.error("file delete error, filepath =" + file.getAbsolutePath());
            }
        }
    }






    public UploadPictureResult uploadPictureByUrl(String fileUrl, String uploadPathPrefix) {
        // 校验图片
        validPicture(fileUrl);
        // 图片上传地址
        String uuid = RandomUtil.randomString(8);
        // 文件名
        String originalFilename = FileUtil.mainName(fileUrl);
        String fileName = String.format("%s_%s.%s", DateUtil.formatDate(new Date()), uuid, originalFilename);
        String filepath = String.format("/%s/%s", uploadPathPrefix, fileName);
        File file = null;
        try {
            // 创建临时文件
            file  = File.createTempFile(filepath, null);
            HttpUtil.downloadFile(fileUrl, file);
            // 上传文件
            PutObjectResult putObjectResult = cosManager.putPictureObject(filepath, file);
            // 解析结果
            ImageInfo imageInfo = putObjectResult.getCiUploadResult().getOriginalInfo().getImageInfo();
            // 返回结果
            UploadPictureResult uploadPictureResult = new UploadPictureResult();
            uploadPictureResult.setUrl(cosClientConfig.getHost() +"/"+ filepath);
            uploadPictureResult.setPicName(fileName);
            uploadPictureResult.setPicSize(FileUtil.size(file));
            uploadPictureResult.setPicWidth(imageInfo.getWidth());
            uploadPictureResult.setPicHeight(imageInfo.getHeight());
            double scale = (double) imageInfo.getWidth() / (double) imageInfo.getHeight();
            uploadPictureResult.setPicScale(scale);
            uploadPictureResult.setPicFormat(imageInfo.getFormat());
            return uploadPictureResult;
        } catch (Exception e) {
            log.info("图片上传失败" ,e);
            throw new BusinessException(ErrorCode.SYSTEM_ERROR, "上传失败");
        }finally {
            deleteTempFile(file);
        }
    }

    /**
     * 根据url校验图片
     * @param fileUrl
     */
    private void validPicture(String fileUrl) {
        //校验非空
        ThrowUtils.throwIf( StringUtils.isBlank(fileUrl), ErrorCode.PARAMS_ERROR,"文件地址为空");
        //校验URL格式
        try {
            new URL(fileUrl);
        } catch (MalformedURLException e) {
            ThrowUtils.throwIf(true, ErrorCode.PARAMS_ERROR,"文件地址格式错误");
        }
        //校验URL协议
        // 只允许http和https
        ThrowUtils.throwIf(!fileUrl.startsWith("http://") && !fileUrl.startsWith("https://"), ErrorCode.PARAMS_ERROR,"文件地址协议错误");
        //发送HEAD 请求文件是否存在
        HttpResponse execute = null;
        try {
            execute = HttpUtil.createRequest(Method.HEAD, fileUrl).execute();
            if (execute.getStatus() != HttpStatus.SC_OK) {
                log.error("文件地址不存在");
                return;
            }
            //文件存在，校验文件后缀
            String contentType = execute.header("Content-Type");
            if (contentType != null) {
                String suffix = FileUtil.getSuffix(contentType);
                final List<String> fileSuffixList = Arrays.asList("image/jpg", "image/jpeg", "image/png", "image/wpeg");
                ThrowUtils.throwIf(!fileSuffixList.contains(suffix), ErrorCode.PARAMS_ERROR,"上传图片格式不正确");
            }
            //文件存在，校验文件大小
            String contentSize = execute.header("Content-Length");
            if (contentSize != null){
                try {
                    ThrowUtils.throwIf(Long.parseLong(contentSize) > 1024 * 1024 * 2, ErrorCode.PARAMS_ERROR,"上传图片不能大于2M");
                }catch (NumberFormatException e){
                    throw new BusinessException(ErrorCode.PARAMS_ERROR,"文件大小格式异常");
                }
            }
        }finally {
            if (execute != null) {
                execute.close();
            }
        }
    }


}




